<template>
  <div class="app-container">
    <div style="display: flex; align-items: center; height: 100%">
      <el-card class="container" shadow="never" style="flex-grow: 2">
        <i class="el-icon-tickets"></i>
        <span>详情</span>
        <div style="margin: 15px auto 0 auto; box-shadow: gray">
          <el-row>
            <el-col :span="4">
              <!-- <div style="background: #cce">L</div> -->
              <div><br/></div>
            </el-col>
            <el-col :span="16">
              <el-row>
                <el-col :span="21" ref="midCol">
                  <!-- <div style="background: #ccd">content</div> -->
                  <el-row>
                    <div style="display: inline">
                      <div style="display: inline">
                        <div v-if="hasImg" style="display: inline">
                          <el-image
                              :src="img_url"
                              :style="{
                            height: table1Height,
                            width: '30%',
                            border: 'dashed gray 1px',
                          }"
                              :preview-src-list="[img_url]"
                              :fit="fitType"
                          />
                        </div>
                        <div
                            v-else
                            style="
                          text-align: center;
                          margin-top: 2rem;
                          display: inline;
                        "
                        >
                          暂无图片
                        </div>
                      </div>
                      <div style="display: inline">
                        <el-table
                            ref="table1"
                            stripe
                            border
                            :show-header="false"
                            :data="tableData1"
                            :style="{ width: '70%', display: 'inline-block' }"
                            :cell-style="tableCell"
                            size="small"
                        >
                          <el-table-column prop="key_cn" label="名称" width="100">
                          </el-table-column>
                          <el-table-column
                              prop="value"
                              label="详情"
                              min-width="120"
                          >
                          </el-table-column>
                        </el-table>
                      </div>
                    </div>
                  </el-row>

                  <el-row></el-row>
                </el-col>
                <el-col :span="3">
                  <!-- <div style="background: #cc1">Btn</div> -->
                  <div style="margin-left: 0.5rem">
                    <el-row>
                      <button
                          style="height: 95px; width: 100%; background: #304156; color: whitesmoke"
                          @click="clickTreeBtn('文本')"
                      >文本属性<br/><br/>信息数据库
                      </button
                      >
                    </el-row>
                    <el-row>
                      <button
                          style="height: 95px; width: 100%; margin-top: 0.5rem; background: #304156; color: whitesmoke"
                          @click="clickTreeBtn('三维模型文件')"
                      >三维模型<br/><br/>信息数据库
                      </button
                      >
                    </el-row>
                  </div>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="21" ref="midCol">
                  <!-- <el-col span="8"> -->
                  <!-- <div style="background: #ccc">img</div> -->

                  <!-- </el-col> -->

                  <el-row>
                    <el-table
                        stripe
                        border
                        :show-header="false"
                        :data="tableData2"
                        style="width: 100%"
                        max-height="500"
                        :cell-style="tableCell"
                        size="small"
                    >
                      <el-table-column prop="key_cn" label="名称" width="100">
                      </el-table-column>
                      <el-table-column prop="value" label="详情" min-width="120">
                      </el-table-column>
                    </el-table>
                  </el-row>
                  <el-row></el-row>
                </el-col>
                <el-col :span="3">
                  <div style="margin-left: 0.5rem">
                    <el-row>
                      <button
                          style="height: 110px; width: 100%; margin-top: 0.5rem; color: whitesmoke; background: #304156"
                          @click="clickTreeBtn('GIS文件')"
                      >GIS<br/><br/>信息数据库
                      </button
                      >
                    </el-row>
                    <el-row>
                      <button
                          style="height: 110px; width: 100%; margin-top: 0.5rem; color: whitesmoke; background: #304156"
                          @click="clickTreeBtn('动画视频')"
                      >动画视频<br><br>信息数据库
                      </button
                      >
                    </el-row>
                  </div>
                </el-col
                >
              </el-row>

              <el-row style="margin-top: 0.5rem">
                <el-col :span="24">
                  <div style="display: flex; justify-content: space-between">
                    <button
                        @click="clickTreeBtn('测绘图图像')"
                        slot="reference"
                        style="width: 22%; height: 75px; background: #304156; color: whitesmoke"
                    >测绘位图图像<br><br>信息数据库
                    </button
                    >

                    <!-- <el-popover> -->
                    <button
                        slot="reference"
                        style="width: 22%; height: 75px; background: #304156; color: whitesmoke"
                        @click="clickTreeBtn('效果图图像')"
                    >效果图图像<br><br>信息数据库
                    </button>
                    <!-- </el-popover> -->
                    <!-- <el-popover> -->
                    <button
                        slot="reference"
                        style="width: 22%; height: 75px; background: #304156; color: whitesmoke"
                        @click="clickTreeBtn('摄影照片')"
                    >摄影图像<br><br>信息数据库
                    </button>
                    <!-- </el-popover> -->
                    <button
                        slot="reference"
                        style="width: 22%; height: 75px; background: #304156; color: whitesmoke"
                        @click="clickTreeBtn('测绘图矢量文件')"
                    >测绘矢量图像<br><br>信息数据库
                    </button>
                  </div>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="4">
              <!-- <div style="background: #ccc">R</div> -->
              <div><br/></div>
            </el-col>
          </el-row>

          <!--        <el-carousel indicator-position="outside">-->
          <!--          <el-carousel-item v-for="item in 4" :key="item">-->
          <!--            <h3>{{ item }}</h3>-->
          <!--          </el-carousel-item>-->
          <!--        </el-carousel>-->
        </div>
      </el-card>
    </div>
    <el-dialog
        v-loading="dialogLoading"
        destroy-on-close
        :title="treeDialogTitle"
        :visible.sync="dialogTreeVisible"
        width="60%"
    >
      <div
          :style="{
          'max-height': dialogContentMaxHeight,
          'overflow-y': 'scroll',
        }"
      >
        <!-- <el-scrollbar > -->
        <el-tree
            :data="treeData"
            :props="treeDefaultProps"
            @node-click="handleNodeClick"
        ></el-tree>
        <el-image-viewer
            v-if="imageViewerVisible"
            :on-close="closeViewer"
            :url-list="imageViewerUrlList"
            :initial-index=imageViewerUrlListIndex
            :z-index="5000"
        />
        <!--
        解释一下z-index属性为什么设为5000，
        查看element-ui image组件的源码
        https://github.com/ElemeFE/element/blob/dev/packages/image/src/main.vue#L62
        可看到z-index默认是2000
        在尝试中发现，el-image可以正常在el-dialog中用
        那咱们自己调用时比它大就行，这样就肯定能在el-dialog的上层了
        不过比较优雅的写法可能是获取一下目前页面的z-index最大值，然后返回一个更大的，而不是写死
        -->
        <el-dialog
            top="3%"
            width="70%"
            title="视频播放"
            :visible.sync="dialogTreeInnerVideoVisible"
            append-to-body
        >
          <div v-if="hasVideo">
            <div style="text-align: center">
              <video id="video" controls width="100%">
                <source :src="video_url" type="video/mp4"/>
                <source :src="video_url" type="video/webm"/>
              </video>
            </div>
          </div>
          <div v-else style="text-align: center">暂无视频</div>
        </el-dialog>
        <!-- </el-scrollbar> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getArchi} from "@/api/info";
import {
  getResourceByInfoId,
  downloadResource,
  getFileTree,
  getImg
} from "@/api/resource";
import request from "@/utils/request";

export default {
  name: "Display",
  components: {
    "el-image-viewer": () =>
        import("element-ui/packages/image/src/image-viewer"),
  },
  data() {
    return {
      dialogLoading: false,
      dialogContentMaxHeight: "500px",
      info_id: 1,
      // 要被展示的信息
      archiInfo: {},

      treeDialogTitle: "",
      treeData: [
        {
          label: "文件夹A",
          children: [
            {
              label: "文件夹B",
              children: [
                {
                  label: "a.file",
                  type: "file",
                },
              ],
            },
            {
              label: "b.png",
              type: "img",
            },
          ],
        },
        {
          label: "一级 2",
          children: [
            {
              label: "二级 2-1",
              children: [
                {
                  label: "三级 2-1-1",
                },
              ],
            },
            {
              label: "二级 2-2",
              children: [
                {
                  label: "三级 2-2-1",
                },
              ],
            },
            {
              label: "c.mp4",
              type: "video",
            },
          ],
        },
        {
          label: "一级 3",
          children: [
            {
              label: "二级 3-1",
              children: [
                {
                  label: "三级 3-1-1",
                },
              ],
            },
            {
              label: "二级 3-2",
              children: [
                {
                  label: "三级 3-2-1",
                },
              ],
            },
          ],
        },
      ],
      treeDefaultProps: {
        children: "children",
        label: "filename",
      },

      fitType: "contain", // 给 el-image 用

      dialogTreeVisible: false,
      dialogTreeInnerVideoVisible: false,

      imageViewerVisible: false, // 显示el-image的查看器
      imageViewerUrlList: [], // el-image查看器的图片地址
      imageViewerUrlListIndex: 0, // el-image查看器图片地址的index
      video_url:
          "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm",
      // video_url: "",
      img_url: "",
      // img_url: "",
      // img_url: "https://img6.bdstatic.com/img/image/pcindex/sunjunpchuazhoutu.JPG",

      table1Height: "1000px",
      // table1Width: "198px",
      activeNames: ["1", "2", "3", "4"],
      docDataWord: {
        name: "doc1.docx",
        url: "path/to/doc",
      },
      docDataPdf: {
        // name: "doc1.pdf",
        // url: "path/to/doc",
      },
      docDataCaj: {
        // name: "doc1.caj",
        // url: "path/to/doc",
      },
      docDataSkp: {
        // name: "doc1.skp",
        // url: "path/to/doc",
      },

      hasVideo: true,
      hasImg: true,
    };
  },
  // beforeUpdate() {
  //   // 获取高度信息
  //   // console.log(this.$refs.table1.$el.offsetHeight);
  //   // setTimeout(() => {
  //   this.table1Height = this.$refs.table1.$el.offsetHeight + "px";
  //   console.log(this.$refs.table1.$el.offsetHeight);
  //   // this.table1Width = (this.$refs.midCol.$el.offsetWidth - this.$refs.table1.$el.offsetHeight - 35 + 'px');
  //   // this.table1Width = "60%";
  //   console.log(this.$refs.midCol.$el.offsetWidth);
  //   console.log(
  //     Number(
  //       this.$refs.midCol.$el.offsetWidth - this.$refs.table1.$el.offsetHeight
  //     )
  //   );
  //   // }, 1000);
  // },
  mounted() {
    this.$nextTick(() => {
      this.table1Height = this.$refs.table1.$el.offsetHeight + "px";
      // console.log(this.$refs.table1.$el.offsetHeight);
      this.dialogContentMaxHeight = window.innerHeight - 350 + "px";
      // console.log(this.dialogContentMaxHeight);
    });

    // 获取 id
    if (this.$route.query.id !== undefined) {
      this.info_id = this.$route.query.id;
    }
    console.log("被展示的infoId => " + this.info_id);

    // 获取对应 id 的建筑的信息
    getArchi(this.info_id).then((response) => {
      console.log("被展示的对象 =>");
      console.log(response.data.list[0]);
      this.archiInfo = Object.assign({}, response.data.list[0]);
      console.log("获取到的附加资源 => ");
      // 获得资源
      // getResourceByInfoId(this.info_id).then((response) => {
      //   console.log(response.data.list);
      //   // 进行url的设置
      //   var that = this; // 为啥要用 that 换呢：因为下面map函数里的this指的就不是vue组件了
      //   response.data.list.map(function (i) {
      //     switch (i.type) {
      //       case "img":
      //         that.img_url =
      //           request.defaults.baseURL + "/resource/downloadResource/" + i.id;
      //         break;
      //       case "video":
      //         that.video_url =
      //           request.defaults.baseURL + "/resource/downloadResource/" + i.id;
      //         // 让video重新加载
      //         document.getElementById("video").load();
      //         break;
      //       default:
      //         that.handleDocData(i);
      //         break;
      //     }
      //   });
      //   console.log(this.video_url);
      //   if (this.video_url === "") {
      //     this.hasVideo = false;
      //   }
      //   if (this.img_url === "") {
      //     this.hasImg = false;
      //   }
      // });
    });
    // 获取图像
    getImg(this.info_id).then(resp => {
      this.img_url = resp.data
    });
    console.log("img_url => ")
    console.log(this.img_url)
  },
  computed: {
    // 单独写 tableData 也行
    tableData1: function () {
      return [
        {
          key_cn: "建筑名称",
          key: "name",
          value: this.archiInfo.name,
        },
        {
          key_cn: "所在城市",
          key: "city",
          value: this.archiInfo.city,
        },
        {
          key_cn: "经度",
          key: "longitude",
          value: this.archiInfo.longitude,
        },
        {
          key_cn: "纬度",
          key: "latitude",
          value: this.archiInfo.latitude,
        },
        {
          key_cn: "海拔",
          key: "altitude",
          value: this.archiInfo.altitude,
        },
      ];
    },
    tableData2: function () {
      return [
        {
          key_cn: "大类",
          key: "largeCate",
          value: this.archiInfo.largeCate,
        },
        {
          key_cn: "中类",
          key: "midCate",
          value: this.archiInfo.midCate,
        },
        {
          key_cn: "小类",
          key: "minCate",
          value: this.archiInfo.minCate,
        },
        {
          key_cn: "年代",
          key: "period",
          value: this.archiInfo.period,
        },
        {
          key_cn: "保护类型",
          key: "protectType",
          value: this.archiInfo.protectType,
        },
        {
          key_cn: "具体描述",
          key: "description",
          value: this.archiInfo.description,
        },
      ];
    },
    tableData: function () {
      return [
        {
          key_cn: "建筑名称",
          key: "name",
          value: this.archiInfo.name,
        },
        {
          key_cn: "所在城市",
          key: "city",
          value: this.archiInfo.city,
        },
        {
          key_cn: "经度",
          key: "longitude",
          value: this.archiInfo.longitude,
        },
        {
          key_cn: "纬度",
          key: "latitude",
          value: this.archiInfo.latitude,
        },
        {
          key_cn: "高度",
          key: "altitude",
          value: this.archiInfo.altitude,
        },
        {
          key_cn: "大类",
          key: "largeCate",
          value: this.archiInfo.largeCate,
        },
        {
          key_cn: "中类",
          key: "midCate",
          value: this.archiInfo.midCate,
        },
        {
          key_cn: "小类",
          key: "minCate",
          value: this.archiInfo.minCate,
        },
        {
          key_cn: "年代",
          key: "period",
          value: this.archiInfo.period,
        },
        {
          key_cn: "保护类型",
          key: "protectType",
          value: this.archiInfo.protectType,
        },
        {
          key_cn: "具体描述",
          key: "description",
          value: this.archiInfo.description,
        },
      ];
    },
  },
  methods: {
    // 点击xxx信息数据库按钮
    clickTreeBtn(title) {
      // function traverseDir(json) {
      //   for (var i = 0, l = json.length; i < l; i++) {
      //     for (var key in json[i]) {
      //       console.log(key + ":" + json[i][key]);
      //     }
      //   }
      // console.log("ok", f);
      // var ret = {};
      // for (var i in f) {
      //   console.log("e", f[i]);
      //   if (f[i].dir == true) {
      //     ret.filename = f[i].filename;
      //     ret.children = traverseDir(f[i]);
      //     ret.dir = true;
      //   } else {
      //     ret.filename = f[i].filename;
      //     ret.children = null;
      //     ret.dir = false;
      //   }
      // }
      // console.log("f", ret);
      //   return ret;
      // }
      function traverseDir(arr, path) {
        var re = {};
        for (var v in arr) {
          var element = arr[v];
          element.path = path + "," + element.filename;
          arr[v] = element;

          if (element.dir == true) {
            let nextPath = path + "," + element.filename;
            traverseDir(element.children, nextPath);
          }
        }
        // console.log(arr);
      }
      this.treeData = [];
      this.dialogLoading = true;

      this.dialogTreeVisible = true;
      this.treeDialogTitle = title;
      var d = null;
      getFileTree(this.info_id, title)
          .then((response) => {
            console.log(response);
            d = response.data;
            d.map((item) => {
              // console.log(item);
            });
            // this.treeData = d;
            traverseDir(d, title);
            console.log("finish", d);
            this.treeData = d;
          })
          .catch(() => {
            this.treeData = null;
          });
      this.dialogLoading = false;
    },

    handleNodeClick(data) {
      console.log(data.path);
      let imgType = ["测绘图图像", "效果图图像", "摄影照片"];
      let videoType = ["动画视频"];
      let fileType = ["测绘图矢量文件", "三维模型文件", "文本", "GIS文件"];
      if (data.dir === false) {
        // if (data.type !== undefined && data.type === "file") {
        if (fileType.includes(this.treeDialogTitle)) {
          console.log("file");
          // console.log(data);
          // 为了实现纯js的点击下载，使用了下面的方法
          // 这个方法比较骚，来源于 https://juejin.cn/post/6994301742225555493
          // 创建a标签
          const link = document.createElement("a");
          // 设置a标签的href（点击地址）
          link.href =
              request.defaults.baseURL +
              "/api/resource/downloadResource/" +
              this.info_id +
              "?filename=" +
              data.path;
          // 设置a标签属性
          link.setAttribute("download", data.label);
          // 点击a标签
          document.body.appendChild(link);
          link.click();
          // 移除a标签
          document.body.removeChild(link);
        }
        // if (data.type !== undefined && data.type === "img") {
        if (imgType.includes(this.treeDialogTitle)) {
          console.log("img");
          this.imageViewerVisible = true;
          // this.imageViewerUrl =
          //     "https://img6.bdstatic.com/img/image/pcindex/sunjunpchuazhoutu.JPG";
          // this.imageViewerUrl =
          //     request.defaults.baseURL +
          //     "/api/resource/downloadResource/" +
          //     this.info_id +
          //     "?filename=" +
          //     data.path;
          var tgtPathList = data.path.split(",");
          var info_id = this.info_id;
          var curIndex = 1;
          var urlList = [];
          function locateNode(arr, level) {
            for (var v in arr) {
              var element = arr[v];
              arr[v] = element;
              if (
                element.dir == true &&
                element.filename == tgtPathList[level]
              ) {
                locateNode(element.children, level + 1);
              } else {
                if (element.filename == tgtPathList[level]) {
                  console.log("OKKKKKK", v, element, arr);
                  curIndex = v;
                  // 找到了之后，进行同级element的组装, 最终组装到urlList里
                  for (var i in arr) {
                    var downloadUrl =
                      request.defaults.baseURL +
                      "/api/resource/downloadResource/" +
                      info_id +
                      "?filename=" +
                      arr[i].path;
                    urlList.push(downloadUrl)
                  }
                  return;
                }
              }
            }
          }
          locateNode(this.treeData, 1);
          this.imageViewerUrlListIndex = Number(curIndex);
          this.imageViewerUrlList = urlList;
          console.log(data);
        }
        // if (data.type !== undefined && data.type === "video") {
        if (videoType.includes(this.treeDialogTitle)) {
          console.log("video");
          this.dialogTreeInnerVideoVisible = true;
          console.log(data);
          this.video_url = request.defaults.baseURL +
              "/api/resource/downloadResource/" +
              this.info_id +
              "?filename=" +
              data.path;
        }
      }
    },

    // 修改样式
    tableCell({row, column, rowIndex, columnIndex}) {
      if (row.key_cn === "具体描述" && column.label === "名称") {
        return "vertical-align:top"; // 详情那个单元格的文字不居中
      }
    },

    // 提取 path 中的文件名
    getFileNameFromPath(path) {
      console.log("path => " + path);
      var fileName = "";
      // 将 path 反转
      path = path.split("").reverse().join("");
      // 遍历 path
      console.log("reversed path => " + path);
      for (const i in path) {
        console.log("i => " + i);
        // Object.hasOwnProperty.call(path, i) 用来确保这个 i 是在 path 这个数组里的, 防止父类制造麻烦
        if (Object.hasOwnProperty.call(path, i)) {
          const element = path[i];
          // console.log(element);
          if (element !== "\\") {
            fileName = fileName + element;
          } else {
            break;
          }
        }
      }
      // 再 reverse 回来
      fileName = fileName.split("").reverse().join("");
      console.log("fileName => " + fileName);
      return fileName;
    },

    // 获得文件的 url 和 name
    handleDocData(i) {
      var fileName = "document." + i.type;
      //检查path是否为空
      if (i.path !== undefined) {
        //2 不为空，获取文件名
        fileName = this.getFileNameFromPath(i.path);
      }
      // var url = "path/to/doc";
      var url = request.defaults.baseURL + "/api/resource/downloadResource/" + i.id;
      var docData = {name: fileName, url: url};

      //3 进入各自的case
      switch (i.type) {
        case "word":
          this.docDataWord = docData;
          break;
        case "caj":
          this.docDataCaj = docData;
          break;
        case "pdf":
          this.docDataPdf = docData;
          break;
        case "skp":
          this.docDataSkp = docData;
          break;
      }
    },

    closeViewer() {
      this.imageViewerVisible = false;
    },
    // 下面两个方法目的是让 el-image-viewer 内滚动的时候不影响外面的页面
    // 来自 https://blog.csdn.net/qq_44712405/article/details/105836883
    // 虽然测试中发现即使没有下面的方法，似乎也不影响，但是还是先留着吧
    // 停止页面滚动
    stopMove() {
      let m = function (e) {
        e.preventDefault();
      };
      document.body.style.overflow = "hidden";
      document.addEventListener("touchmove", m, {passive: false}); // 禁止页面滑动
    },
    // 开启页面滚动
    move() {
      let m = function (e) {
        e.preventDefault();
      };
      document.body.style.overflow = "auto"; // 出现滚动条
      document.removeEventListener("touchmove", m, {passive: true});
    },
  },
};
</script>

<style scoped>
.spec-dialog .el-dialog__body {
  padding: 3px 30px;
  overflow-y: auto;
  height: calc(100vh - 140px);
}
</style>
